package com.wonder.app.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vtuzx.core.utils.VtuzxUtil;
import com.wonder.app.domain.*;
import com.wonder.app.mapper.*;
import com.wonder.app.request.PrdReportInspectRequest;
import com.wonder.app.request.StkTransferRequest;
import com.wonder.app.service.*;
import com.wonder.common.utils.DateUtils;
import com.wonder.constant.BillType;
import com.wonder.constant.IXqcConst;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class StkTransferImpl extends ServiceImpl<StkTransferDao, StkTransfer> implements StkTransferService {


    /** 日志 */
    private static final Logger _logger = LoggerFactory.getLogger(StkApplyServiceImpl.class);
    @Autowired
    private StkTransferService stkTransferService;
    @Autowired
    private  StkTransferDao stkTransferDao;
    @Autowired
    private StkTransferDetailDao stkTransferDetailDao;
    @Autowired
    private StkTransferDetailService stkTransferDetailService;

    @Autowired
    private StkTransferAppDetailDao stkTransferAppDetailDao;

    @Autowired
    private SyncKingdeeOrderService syncKingdeeOrderService;


    @Autowired
    private TrayDao trayDao;

    @Autowired
    private TrayService trayService;


    @Override
    public IPage<StkTransfer> selectList(StkTransferRequest stkTransferRequest, Page<StkTransfer> page) {
        LambdaQueryWrapper<StkTransfer> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (stkTransferRequest.getFBillNo() != null){
            lambdaQueryWrapper.like(StkTransfer::getFBillNo,stkTransferRequest.getFBillNo());
        }

        if (stkTransferRequest.getFKDBILLNO() != null){
            lambdaQueryWrapper.like(StkTransfer::getFKDBILLNO,stkTransferRequest.getFKDBILLNO());
        }

        if (stkTransferRequest.getFBILLNOMO() != null){
            lambdaQueryWrapper.like(StkTransfer::getFBILLNOMO,stkTransferRequest.getFBILLNOMO());
        }

        if (stkTransferRequest.getFCREATEUSER() != null){
            lambdaQueryWrapper.like(StkTransfer::getFCREATEUSER,stkTransferRequest.getFCREATEUSER());
        }

        if (stkTransferRequest.getFDATE() != null){
            Date[] orderDate = stkTransferRequest.getFDATE();
            if(orderDate.length>0)
                lambdaQueryWrapper.ge(StkTransfer::getFDATE, orderDate[0]);
            if(orderDate.length==2)
                lambdaQueryWrapper.le(StkTransfer::getFDATE,orderDate[1]);
        }
        lambdaQueryWrapper.orderByDesc(StkTransfer::getFDATE);


        if (stkTransferRequest.getCreateTime() != null){
            Date[] orderDate = stkTransferRequest.getCreateTime();
            if(orderDate.length>0)
                lambdaQueryWrapper.ge(StkTransfer::getCreateTime, orderDate[0]);
            if(orderDate.length==2)
                lambdaQueryWrapper.le(StkTransfer::getCreateTime,orderDate[1]);
        }
        lambdaQueryWrapper.orderByDesc(StkTransfer::getCreateTime);

        if (stkTransferRequest.getFSTOCKPEL() != null){
            lambdaQueryWrapper.like(StkTransfer::getFSTOCKPEL,stkTransferRequest.getFSTOCKPEL());
        }

        if (stkTransferRequest.getFINDEPTNAME() != null){
            lambdaQueryWrapper.like(StkTransfer::getFINDEPTNAME,stkTransferRequest.getFINDEPTNAME());
        }

        if (stkTransferRequest.getFOUTDEPTNAME() != null){
            lambdaQueryWrapper.like(StkTransfer::getFOUTDEPTNAME,stkTransferRequest.getFOUTDEPTNAME());
        }

        Page<StkTransfer> selectPage = this.baseMapper.selectPage(page, lambdaQueryWrapper);
        return selectPage;
    }
    /**
     * 直接调拨单明细详情
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> getStkTransferDetail(Map<String, Object> map) {
        String billNo = map.get("billNo").toString();
        StkTransfer stktransferform = stkTransferDao.selectOne(new LambdaQueryWrapper<StkTransfer>()
                .eq(StkTransfer::getFBillNo,billNo));
        List<StkTransferDetail> stktransferdetailList = stkTransferDetailDao.selectList(new LambdaQueryWrapper<StkTransferDetail>()
                .eq(StkTransferDetail::getFBILLNO,billNo));
        Map<String,Object> data = new HashMap<>();
        data.put("data",stktransferform);
        data.put("dataList",stktransferdetailList);
        return data;
    }

    /**
     * 调拨单列表手机端
     * @param map
     * @return
     */
    @Override
    public Map<String, Object> getTransferList(Map<String, Object> map) {
        int pageIndex = VtuzxUtil.getInt(map,"pageIndex");
        int pageSize = VtuzxUtil.getInt(map,"pageSize");
        String billNo = VtuzxUtil.getString(map,"billNo");//调拨单号
        List<StkTransfer> dataList = stkTransferDao.getTransferList(pageSize,pageIndex * pageSize,billNo);
        Map<String,Object> data = new HashMap<>();
        data.put("dataList",dataList);
        return data;
    }

    /**
     * 生成调拨单
     * @param map
     * @return
     */
    @Override
    public boolean createTransfer(Long user_id,String userName,Map<String, Object> map) throws Exception {
        String stockNo = VtuzxUtil.getString(map,"stockNo");//调入仓库
        String locationNo = VtuzxUtil.getString(map,"locationNo");//调入仓位
        List<StkTransferDetail> stkTransferDetails = stkTransferDetailDao.selectList(new LambdaQueryWrapper<StkTransferDetail>()
                .eq(StkTransferDetail::getTEMP, true)
                .eq(StkTransferDetail::getUSERID, user_id)
                .isNull(StkTransferDetail::getTransferAppId));
        String transferNo =  IXqcConst.createBillNo(BillType.DBRK);//生成中台调拨单号
        //添加调拨外层数据
        StkTransfer stkTransfer = new StkTransfer();
        stkTransfer.setFBillNo(transferNo);
        stkTransfer.setCreateTime(new Date());
        stkTransfer.setFCREATEUSER(userName);
        stkTransfer.setFSTATE(false);
        Date date = DateUtils.adjustDateTransfer(new Date());
        stkTransfer.setFDATE(date);


        List<String> trayNoList = new ArrayList<>();//托盘编号集合需要修改托盘的仓位状态
        for (StkTransferDetail stkTransferDetail : stkTransferDetails ){
            stkTransferDetail.setFDestStockId(stockNo);//调入仓库
            stkTransferDetail.setFDestStockLocId(locationNo);//调入仓位
            stkTransferDetail.setTEMP(false);
            stkTransferDetail.setFBILLNO(transferNo);
            String trayNo = stkTransferDetail.getTRAYNO();
            if(!trayNoList.contains(trayNo)){
                trayNoList.add(trayNo);
            }
        }
        if (!VtuzxUtil.isEmpty(trayNoList)){
            List<Tray> trays = trayDao.selectList(new LambdaQueryWrapper<Tray>()
                    .in(Tray::getFBILLNO, trayNoList));
            for (Tray tray : trays){
                tray.setSTOCKNO(stockNo);
                tray.setLOCATIONNO(locationNo);
            }
            boolean b = trayService.saveOrUpdateBatch(trays);
        }
        //调拨单传入金蝶
        try {
            syncKingdeeOrderService.syncTransferAllocation(user_id,stkTransfer,stkTransferDetails);
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }

        boolean save = stkTransferService.save(stkTransfer);
        boolean save1 = stkTransferDetailService.saveOrUpdateBatch(stkTransferDetails);
        return save && save1;
    }

    /**
     * 创建调拨单临时数据
     * @param userId
     * @param userName
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public boolean createTransferTemp(Long userId, String userName, Map<String, Object> map) throws Exception {
        List<Map<String,Object>> trayDataList = VtuzxUtil.getObject(map,"trayData");
//        Map<String,Object> currentData = VtuzxUtil.getObject(map,"currentData");//调拨申请详情信息
//        Integer detailId = 0;
//        if (!VtuzxUtil.isEmpty(currentData)){
//            detailId = VtuzxUtil.getInt(currentData,"id");//调拨申请详情id
//        }
        Integer headerId = VtuzxUtil.getInt(map,"headerId");//调拨申请单据头fid
        //查询调拨申请单据体,判断当前的托盘件号在单据体中是否包含
        List<StkTransferAppDetaill> stkTransferAppDetaillList = stkTransferAppDetailDao.selectList(new LambdaQueryWrapper<StkTransferAppDetaill>()
                .eq(StkTransferAppDetaill::getFID, headerId));
        List<String> materialNoList = new ArrayList<>();
        Map<String,Object> materialMap = new HashMap<>();//key:物料编码 val:调拨申请单据体entryid

        for (StkTransferAppDetaill stkTransferAppDetaill : stkTransferAppDetaillList){
            String fmaterialno = stkTransferAppDetaill.getFMATERIALNO();
            if (!materialNoList.contains(fmaterialno)){
                materialNoList.add(fmaterialno);
            }
            materialMap.put(fmaterialno,stkTransferAppDetaill.getFENTRYID());
        }

        List<StkTransferDetail> stkTransferDetailList = new ArrayList<>();
        for (Map<String,Object> trayData : trayDataList){
            String trayNo = VtuzxUtil.getString(trayData,"fbillno");//托盘单号
//            //判断调拨单是否已经有这个托号
//            StkTransferDetail currentDetail = stkTransferDetailDao.selectOne(new LambdaQueryWrapper<StkTransferDetail>()
//                    .eq(StkTransferDetail::getTRAYNO, trayNo)
//                    .eq(StkTransferDetail::getTEMP, true));
//            if (!VtuzxUtil.isEmpty(currentDetail)){
//                throw new RuntimeException("当前托号已经添加");
//            }
//
//            Tray tray = trayDao.selectOne(new LambdaQueryWrapper<Tray>()
//                    .eq(Tray::getFBILLNO, trayNo));
//            //如果没有仓库和仓位信息的话不让添加，不然无法调拨
//            if (VtuzxUtil.isEmpty(tray.getSTOCKNO())){
//                throw new RuntimeException("托盘还未入库,无法调拨");
//            }
            String fmaterialnumber = VtuzxUtil.getString(trayData,"fmaterialnumber");
//            if (!materialNoList.contains(fmaterialnumber)){
//                throw new RuntimeException("调拨申请明细中没有包含当前件号,请确认");
//            }
            //调拨详情表添加临时数据
            StkTransferDetail stkTransferDetail = new StkTransferDetail();
            stkTransferDetail.setFMATERIALNUMBER(fmaterialnumber);
            stkTransferDetail.setFMATERIALNAME(VtuzxUtil.getString(trayData,"fmaterialname"));
            stkTransferDetail.setFSPECIFICATION(VtuzxUtil.getString(trayData,"itemnumber"));
            stkTransferDetail.setFUNITNAME(VtuzxUtil.getString(trayData,"funitname"));
            stkTransferDetail.setFUNITID(VtuzxUtil.getString(trayData,"funitid"));
            stkTransferDetail.setFQTY(VtuzxUtil.getDouble(trayData,"fqty"));//数量
            if (!VtuzxUtil.isEmpty(VtuzxUtil.getString(trayData,"flot"))){
                stkTransferDetail.setFLOT(VtuzxUtil.getString(trayData,"flot"));
            }
            stkTransferDetail.setFSrcStockId(VtuzxUtil.getString(trayData,"stockno"));
            stkTransferDetail.setFSrcStockName(VtuzxUtil.getString(trayData,"stockname"));
            stkTransferDetail.setFSrcStockLocName(VtuzxUtil.getString(trayData,"locationno"));
            stkTransferDetail.setFSrcStockLocId(VtuzxUtil.getString(trayData,"locationno"));
            stkTransferDetail.setProductionDate(DateUtils.strToDate(VtuzxUtil.getString(trayData,"productiondate"),"yyyy-MM-dd HH:mm:ss"));
            if (!VtuzxUtil.isEmpty(trayNo)){
                stkTransferDetail.setTRAYNO(trayNo);
            }
            stkTransferDetail.setTEMP(true);
            stkTransferDetail.setUSERID(userId);
            stkTransferDetail.setTransferAppId(headerId);//调拨申请单据头fid
            Integer entryId = VtuzxUtil.getInt(materialMap,fmaterialnumber);
            stkTransferDetail.setTransferAppDetailId(entryId);//调拨申请单据体entryid
//            stkTransferDetail.setProductionDate(DateUtils.strToDate(VtuzxUtil.getString(trayData,"productiondate"),""))
            stkTransferDetailList.add(stkTransferDetail);
        }


        boolean save = stkTransferDetailService.saveOrUpdateBatch(stkTransferDetailList);

        return save;
    }

    /**
     * 获取调拨单的临时数据
     * @param userId
     * @param userName
     * @param map
     * @return
     */
    @Override
    public Map<String,Object> getTransferTemp(Long userId, String userName, Map<String, Object> map) {
        List<StkTransferDetail> stkTransferDetails = stkTransferDetailDao.selectList(new LambdaQueryWrapper<StkTransferDetail>()
                .eq(StkTransferDetail::getTEMP, true)
                .eq(StkTransferDetail::getUSERID, userId)
                .isNull(StkTransferDetail::getTransferAppId));
        Map<String,Object> data = new HashMap<>();
        data.put("dataList",stkTransferDetails);

        return data;
    }

    /**
     * 删除调拨单临时数据
     * @param userId
     * @param userName
     * @param map
     * @return
     */
    @Override
    public boolean deleteTransferTemp(Long userId, String userName, Map<String, Object> map) {
        Long id = VtuzxUtil.getLong(map,"id");
        boolean b = stkTransferDetailService.removeById(id);
        return b;
    }

    /**
     * 根据调拨申请生成调拨单
     * @param user_id
     * @param userName
     * @param stkTransferApp
     * @param stkTransferAppDetaillList
     * @return
     * @throws Exception
     */
    @Override
    public Boolean createTransferByYTransferApp(Long user_id, String userName, StkTransferApp stkTransferApp, List<StkTransferAppDetaill> stkTransferAppDetaillList) throws Exception {
        String transferNo =  IXqcConst.createBillNo(BillType.DBRK);//生成中台调拨单号
        //添加调拨外层数据
        StkTransfer stkTransfer = new StkTransfer();
        stkTransfer.setFBillNo(transferNo);
        stkTransfer.setCreateTime(new Date());
        stkTransfer.setFCREATEUSER(userName);
        stkTransfer.setFSTATE(false);
        stkTransfer.setFNote(stkTransferApp.getFBILLNO());//备注先存申请单号

        List<StkTransferDetail> transferDetailList = new ArrayList<>();
        for (StkTransferAppDetaill stkTransferAppDetaill : stkTransferAppDetaillList){
            StkTransferDetail stkTransferDetail = new StkTransferDetail();
            stkTransferDetail.setFBILLNO(transferNo);
            stkTransferDetail.setFMATERIALNUMBER(stkTransferAppDetaill.getFMATERIALNO());
            stkTransferDetail.setFMATERIALNAME(stkTransferAppDetaill.getFMATERIALNAME());
            stkTransferDetail.setFSPECIFICATION(stkTransferAppDetaill.getFSPECIFICATION());
            stkTransferDetail.setFUNITID(stkTransferAppDetaill.getFUNITNO());
            stkTransferDetail.setFUNITNAME(stkTransferAppDetaill.getFUNITNAME());
            stkTransferDetail.setFQTY(stkTransferAppDetaill.getFQTY());
            stkTransferDetail.setFSrcStockId(stkTransferAppDetaill.getFSTOCKNO());//调出仓库编码
            stkTransferDetail.setFSrcStockName(stkTransferAppDetaill.getFSTOCKNAME());//调出仓库名称
            stkTransferDetail.setFSrcStockLocId(stkTransferAppDetaill.getFLOCATIONO());//调出仓位
            stkTransferDetail.setFSrcStockLocName(stkTransferAppDetaill.getFLOCATIONAME());//调出仓位名称
            stkTransferDetail.setFDestStockId(stkTransferAppDetaill.getFSTOCKINNO());//调入仓库编码
            stkTransferDetail.setFDestStockName(stkTransferAppDetaill.getFSTOCKINNAME());//调入仓库名称
            stkTransferDetail.setFDestStockLocId(stkTransferAppDetaill.getFLOCATIONINNO());//调入仓位编码
            stkTransferDetail.setFDestStockLocName(stkTransferAppDetaill.getFLOCATIONINNAME());//调入仓位名称
            stkTransferDetail.setTEMP(false);
            stkTransferDetail.setUSERID(user_id);
            transferDetailList.add(stkTransferDetail);
        }

        boolean res = stkTransferService.saveOrUpdate(stkTransfer);
        boolean detailRes = stkTransferDetailService.saveOrUpdateBatch(transferDetailList);

        //调拨单传金蝶
//        syncKingdeeOrderService.syncTransfer(user_id,stkTransferApp,stkTransferAppDetaillList);

        return res && detailRes;
    }

    @Override
    public boolean createTransferTempByTray(Long userId, String userName, Map<String, Object> map) throws Exception {
        List<Map<String,Object>> trayDataList = VtuzxUtil.getObject(map,"trayData");
//        Map<String,Object> currentData = VtuzxUtil.getObject(map,"currentData");//调拨申请详情信息
//        Integer detailId = 0;
//        if (!VtuzxUtil.isEmpty(currentData)){
//            detailId = VtuzxUtil.getInt(currentData,"id");//调拨申请详情id
//        }

        List<StkTransferDetail> stkTransferDetailList = new ArrayList<>();
        for (Map<String,Object> trayData : trayDataList){
            String trayNo = VtuzxUtil.getString(trayData,"fbillno");//托盘单号
            //判断调拨单是否已经有这个托号
            StkTransferDetail currentDetail = stkTransferDetailDao.selectOne(new LambdaQueryWrapper<StkTransferDetail>()
                    .eq(StkTransferDetail::getTRAYNO, trayNo)
                    .eq(StkTransferDetail::getTEMP, true));
            if (!VtuzxUtil.isEmpty(currentDetail)){
                throw new RuntimeException("当前托号已经添加");
            }

            Tray tray = trayDao.selectOne(new LambdaQueryWrapper<Tray>()
                    .eq(Tray::getFBILLNO, trayNo));
            //如果没有仓库和仓位信息的话不让添加，不然无法调拨
            if (VtuzxUtil.isEmpty(tray.getSTOCKNO())){
                throw new RuntimeException("托盘还未入库,无法调拨");
            }
            String fmaterialnumber = VtuzxUtil.getString(trayData,"fmaterialnumber");
            //调拨详情表添加临时数据
            StkTransferDetail stkTransferDetail = new StkTransferDetail();
            stkTransferDetail.setFMATERIALNUMBER(fmaterialnumber);
            stkTransferDetail.setFMATERIALNAME(VtuzxUtil.getString(trayData,"fmaterialname"));
            stkTransferDetail.setFSPECIFICATION(VtuzxUtil.getString(trayData,"itemnumber"));
            stkTransferDetail.setFUNITNAME(VtuzxUtil.getString(trayData,"funitname"));
            stkTransferDetail.setFUNITID(VtuzxUtil.getString(trayData,"funitid"));
            stkTransferDetail.setFQTY(VtuzxUtil.getDouble(trayData,"fqty"));//数量
            if (!VtuzxUtil.isEmpty(VtuzxUtil.getString(trayData,"flot"))){
                stkTransferDetail.setFLOT(VtuzxUtil.getString(trayData,"flot"));
            }
            stkTransferDetail.setFSrcStockId(VtuzxUtil.getString(trayData,"stockno"));
            stkTransferDetail.setFSrcStockName(VtuzxUtil.getString(trayData,"stockname"));
            stkTransferDetail.setFSrcStockLocName(VtuzxUtil.getString(trayData,"locationno"));
            stkTransferDetail.setFSrcStockLocId(VtuzxUtil.getString(trayData,"locationno"));
            stkTransferDetail.setTRAYNO(trayNo);
            stkTransferDetail.setTEMP(true);
            stkTransferDetail.setUSERID(userId);
            stkTransferDetail.setProductionDate(DateUtils.strToDate(VtuzxUtil.getString(trayData,"productiondate"),"yyyy-MM-dd HH:mm:ss"));
//            stkTransferDetail.setTransferAppId(headerId);//调拨申请单据头fid
//            Integer entryId = VtuzxUtil.getInt(materialMap,fmaterialnumber);
//            stkTransferDetail.setTransferAppDetailId(entryId);//调拨申请单据体entryid
            stkTransferDetailList.add(stkTransferDetail);

        }



        boolean save = stkTransferDetailService.saveOrUpdateBatch(stkTransferDetailList);

        return save;
    }


}

